// app/rfq/page.tsx

import * as React from "react";
import { Metadata } from "next";
import { type SearchParams } from "@/types/table";
import { Shell } from "@/components/shell";
import { DataTableSkeleton } from "@/components/data-table/data-table-skeleton";
import { HelpCircle, Package, FileText, ClipboardList, Layers } from "lucide-react";
import {
  Tabs,
  TabsContent,
  TabsList,
  TabsTrigger,
} from "@/components/ui/tabs";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { RfqTable } from "@/lib/rfq-last/table/rfq-table";
import { getRfqs } from "@/lib/rfq-last/service";
import { searchParamsRfqCache } from "@/lib/rfq-last/validations";
import { InformationButton } from "@/components/information/information-button";

export const metadata: Metadata = {
  title: "RFQ 관리",
  description: "RFQ 견적 요청 관리 시스템",
};

interface RfqPageProps {
  searchParams: Promise<SearchParams>;
}


// 탭별 데이터 카운트를 가져오는 함수
async function getTabCounts() {
  try {
    const [generalData, preBiddingData, itbData, rfqData] = await Promise.all([
      getRfqs({ page: 1, perPage: 1, sort: [], filters: [], joinOperator: "and", search: "", rfqCategory: "general" }),
      getRfqs({ page: 1, perPage: 1, sort: [], filters: [], joinOperator: "and", search: "", rfqCategory: "pre_bidding" }),
      getRfqs({ page: 1, perPage: 1, sort: [], filters: [], joinOperator: "and", search: "", rfqCategory: "itb" }),
      getRfqs({ page: 1, perPage: 1, sort: [], filters: [], joinOperator: "and", search: "", rfqCategory: "rfq" }),
    ]);

    return {
      general: generalData.total || 0,
      pre_bidding: preBiddingData.total || 0,
      itb: itbData.total || 0,
      rfq: rfqData?.total || 0,
    };
  } catch (error) {
    console.error("Error fetching tab counts:", error);
    return {
      general: 0,
      pre_bidding: 0,
      itb: 0,
      rfq: 0,
    };
  }
}

export default async function RfqPage(props: RfqPageProps) {
  const searchParams = await props.searchParams;
  
  // nuqs 기반 파라미터 파싱
  const search = searchParamsRfqCache.parse(searchParams);
  
  
  // 탭별 데이터 카운트 가져오기
  const tabCounts = await getTabCounts();

  console.log(search.rfqCategory ,"search.rfqCategory ")
  
  // 현재 선택된 탭 (URL 파라미터에서 가져오거나 기본값 'all')
  const currentTab = search.rfqCategory || "itb";

  // 각 탭별로 데이터 프리패칭
//   const allData = await getRfqs({ ...search, rfqCategory: "all" });
  const generalData = await getRfqs({ ...search, rfqCategory: "general" });
  const preBiddingData = await getRfqs({ ...search, rfqCategory: "pre_bidding" });
  const itbData = await getRfqs({ ...search, rfqCategory: "itb" });
  const rfqData = await getRfqs({ ...search, rfqCategory: "rfq" });

  return (
    <Shell className="gap-4">
      {/* 헤더 */}
      <div className="flex items-center justify-between space-y-2">
        <div className="flex items-center gap-2">
          <h2 className="text-2xl font-bold tracking-tight">
            견적목록관리
          </h2>
          <InformationButton pagePath="evcp/rfq-last" />
        </div>
      </div>

      {/* 탭 컨테이너 */}
      <Tabs defaultValue={currentTab} className="w-full flex-1 flex flex-col overflow-hidden">

      <TabsList className="grid w-full max-w-[800px] grid-cols-4 flex-shrink-0">
         
          <TabsTrigger value="itb" className="relative">
            <Package className="mr-2 h-4 w-4" />
            ITB
            {tabCounts.itb > 0 && (
              <Badge variant="secondary" className="ml-2 text-xs">
                {tabCounts.itb}
              </Badge>
            )}
          </TabsTrigger>
          <TabsTrigger value="rfq" className="relative">
            <ClipboardList className="mr-2 h-4 w-4" />
            RFQ
            {tabCounts.rfq > 0 && (
              <Badge variant="secondary" className="ml-2 text-xs">
                {tabCounts.rfq}
              </Badge>
            )}
          </TabsTrigger>
          <TabsTrigger value="general" className="relative">
            <FileText className="mr-2 h-4 w-4" />
            일반견적
            {tabCounts.general > 0 && (
              <Badge variant="secondary" className="ml-2 text-xs">
                {tabCounts.general}
              </Badge>
            )}
          </TabsTrigger>
          <TabsTrigger value="pre_bidding" className="relative">
            <FileText className="mr-2 h-4 w-4" />
            사전견적(입찰)
            {tabCounts.pre_bidding > 0 && (
              <Badge variant="secondary" className="ml-2 text-xs">
                {tabCounts.pre_bidding}
              </Badge>
            )}
          </TabsTrigger>
        </TabsList>

 
        {/* 일반견적 탭 */}
        <TabsContent value="general" className="mt-4 flex-1 overflow-hidden relative">
          <React.Suspense
            fallback={
              <DataTableSkeleton
                columnCount={13}
                searchableColumnCount={4}
                filterableColumnCount={8}
                cellWidths={[
                  "3rem",   // checkbox
                  "9rem",   // rfqCode
                  "7rem",   // status
                  "8rem",   // rfqType
                  "15rem",  // rfqTitle
                  "8rem",   // projectCode
                  "12rem",  // projectName
                  "8rem",   // picName
                  "5rem",   // rfqSendDate
                  "5rem",   // dueDate
                  "5rem",   // vendorCount
                  "5rem",   // quotationReceived
                  "5rem",   // actions
                ]}
                shrinkZero
              />
            }
          >
            <RfqTable
              data={generalData}
              rfqCategory="general"
            />
          </React.Suspense>
        </TabsContent>

        {/* 사전견적(입찰) 탭 */}
        <TabsContent value="pre_bidding" className="mt-4 flex-1 overflow-hidden relative">
          <React.Suspense
            fallback={
              <DataTableSkeleton
                columnCount={13}
                searchableColumnCount={4}
                filterableColumnCount={8}
                cellWidths={[
                  "3rem",   // checkbox
                  "9rem",   // rfqCode
                  "7rem",   // status
                  "8rem",   // rfqType
                  "15rem",  // rfqTitle
                  "8rem",   // projectCode
                  "12rem",  // projectName
                  "8rem",   // picName
                  "5rem",   // rfqSendDate
                  "5rem",   // dueDate
                  "5rem",   // vendorCount
                  "5rem",   // quotationReceived
                  "5rem",   // actions
                ]}
                shrinkZero
              />
            }
          >
            <RfqTable
              data={preBiddingData}
              rfqCategory="pre_bidding"
            />
          </React.Suspense>
        </TabsContent>

        {/* ITB 탭 */}
        <TabsContent value="itb" className="mt-4 flex-1 overflow-hidden relative">
          <React.Suspense
            fallback={
              <DataTableSkeleton
                columnCount={14}
                searchableColumnCount={4}
                filterableColumnCount={9}
                cellWidths={[
                  "3rem",   // checkbox
                  "9rem",   // rfqCode
                  "7rem",   // status
                  "10rem",  // projectCompany
                  "8rem",   // projectFlag
                  "10rem",  // projectSite
                  "6rem",   // smCode
                  "8rem",   // projectCode
                  "12rem",  // projectName
                  "8rem",   // picName
                  "5rem",   // rfqSendDate
                  "5rem",   // dueDate
                  "5rem",   // vendorCount
                  "5rem",   // actions
                ]}
                shrinkZero
              />
            }
          >
            <RfqTable
              data={itbData}
              rfqCategory="itb"
            />
          </React.Suspense>
        </TabsContent>

        {/* RFQ(PR) 탭 */}
        <TabsContent value="rfq" className="mt-4 flex-1 overflow-hidden relative">
          <React.Suspense
            fallback={
              <DataTableSkeleton
                columnCount={15}
                searchableColumnCount={4}
                filterableColumnCount={10}
                cellWidths={[
                  "3rem",   // checkbox
                  "9rem",   // rfqCode
                  "7rem",   // status
                  "8rem",   // prNumber
                  "8rem",   // prIssueDate
                  "8rem",   // series
                  "8rem",   // projectCode
                  "12rem",  // projectName
                  "8rem",   // itemCode
                  "12rem",  // itemName
                  "8rem",   // picName
                  "5rem",   // rfqSendDate
                  "5rem",   // dueDate
                  "5rem",   // vendorCount
                  "5rem",   // actions
                ]}
                shrinkZero
              />
            }
          >
            <RfqTable
              data={rfqData}
              rfqCategory="rfq"
            />
          </React.Suspense>
        </TabsContent>
      </Tabs>
    </Shell>
  );
}